
const osubmit = document.getElementById("submit");
const setAccount = document.querySelector("#setAccount");
const setPassword = document.querySelector("#setPassword");
const setPassword2 = document.querySelector("#setPassword2");

//用户名验证
osubmit.onclick = function () {
    var reg = /^[a-zA-Z]{1}[A-Z|a-z|0-9]{5,16}/;//账号
    var reg1 = /[A-Za-z]+[0-9]+/;//密码
    if (reg.test(setAccount.value) && setAccount.value.length >= 6 && setAccount.value.length <= 17) {
        document.querySelector(".set1").innerHTML = "&radic;";
        if (reg1.test(setPassword.value) && setPassword.value.length >= 6 && setPassword.value.length <= 8) {
            document.querySelector(".set2").innerHTML = "&radic;";
            if (setPassword2.value == setPassword.value && setPassword.value != "") {
                document.querySelector(".set3").innerHTML = "&radic;";
                console.log("ok")
                ajax("http://localhost:3000/api", function (res) {
                    res = JSON.parse(res);

                    if (res.code === 0) {
                        alert(res.title);
                        setAccount.value = "";
                        setAccount.focus();
                    } else if (res.code === 1) {
                        if (confirm("注册成功，是否跳转到登录")) {
                            location.href = "./login.html";
                        }
                    }
                }, {
                    type: "register",
                    username: setAccount.value,
                    password: setPassword.value
                })
            }
            else { document.querySelector(".set3").innerHTML = "&times;"; }
        }
        else { document.querySelector(".set2").innerHTML = "&times;"; }

    }
    else { document.querySelector(".set1").innerHTML = "&times;"; }

}



function ajax(url, callback, data) {
    let str = "";
    for (let i in data) {
        str += `${i}=${data[i]}&`
    }
    url += "?" + str;
    const xhr = new XMLHttpRequest();
    xhr.open("get", url)
    xhr.onload = function () {
        if (xhr.status === 200) {
            callback(xhr.responseText)
        }
    }
    xhr.send();
}


